$(function() {

    $.init();

	var cache = [];
    var remindPage = {
        page: 1,
        size: 8
    };
    var talkPage = {
    	page: 1,
        size: 8
    };
    var loading = true;
    var curPage = 'remind';

    $(document).on('click', 'header .title span', onSwitch);
    $(document).on('click', '.filter-nav', tabHandle);
    $(document).on('click', '.j-top', topHandle);
    $(document).on('click', '.j-agree', agreeHandle);
    $(document).on('click', '.j-refuse', refuseHandle);
    $(document).on('click', '.j-return', returnHandle);
    $(document).on('click', '.common', lookInfoHandle);
    $('.infinite-scroll-bottom').on('infinite', infiniteHandle());

    renderRemindNumber();
    renderRemind('top');

    function lookInfoHandle(e) {
    	var $target = $(e.currentTarget);
    	if($(e.target).hasClass('j-agree')) {
    		return;
    	}
    	if($(e.target).hasClass('j-refuse')) {
    		return;
    	}
    	if($(e.target).hasClass('j-top')) {
    		return;
    	}
    	if($(e.currentTarget).data('apply')){
			window.location = './travel_info.html?targetid='+$target.data('id')+'&selfid='+SELFID+'&from=remind';
			return;
		}
    	fetchMax(function(amount) {
			$.confirm('您今天还有' + amount + '次查看详情的机会', function(isAdd){
				window.location = './travel_info.html?targetid='+$target.data('id')+'&selfid='+SELFID+'&from=remind';
			})
		});
    }

    function fetchMax(callback) {
		$.ajax({
			type: 'GET',
			url: HOST + '/api/travel/remainViewNum?openid=' + SELFID,
			success: function(res) {
				callback && callback(res.content);
			},
			error: function() {
				callback(3);
			}
		});
	}

    function onSwitch(e) {
        var $target = $(e.target);
        var type = $target.data('type');
        curPage = type;
        $target.addClass('active').siblings().removeClass('active');
        $('.content-item').hide();
        $('.content-'+type).show();
        remindPage.page = 1;
        talkPage.page = 1;
        if(type == 'talk') {
            renderTalk();
        }else if(type == 'remind') {
            renderRemind('top');
        }else{}
    }

    function tabHandle(e) {
    	var $target;
    	var type;
    	var html = '';
    	if(typeof e == 'object') {
    		$target = $(e.target).closest('.nav-item');
    		if($target.length == 0) {
	        	return;
	        }
	        if($target.hasClass('active')) {
	        	return;
	        }
	        type = $target.attr('data-type')
    	}else{
    		type = e;
    	}
    	if($target) {
    		$target.addClass('active').siblings().removeClass('active');
    	}
        remindPage.page = 1;
        $('.infinite-scroll-preloader').remove();
        renderRemind(type);
        renderRemindNumber();
    }

    function topHandle(e) {
        var $target = $(e.target);
        e.stopPropagation();
        //正在ajax或已经点过赞或已经申请过
        if($target.hasClass('agree-active') || $target.hasClass('ajaxing')) {
            return;
        }
        $target.addClass('ajaxing');
        $.ajax({
            url: HOST + '/api/travel/support',
            type: 'post',
            data: JSON.stringify({
                openid: SELFID,
                supportedOpenid: $target.closest('.top').data('id')
            }),
            success: function(res){
                if(res.content == 'success') {
                    $(e.target).addClass('agree-active');
                    $target.find('em').html(+$target.find('em').html()+1);
                }else{
                    $.alert(res.content);
                }
                $(e.target).removeClass('ajaxing');
            }
        });
    }

    function renderRemindNumber() {
        $.ajax({
            type: 'GET',
            url: HOST + '/api/user/remind/survey',
            data: {
                openid: SELFID
            },
            success: function(res) {
                var data = res.content;
                $('.content .filter-nav .nav-total').each(function(index, item) {
                    $item = $(item);
                    if(index == 0) {
                        $item.html(data.topNum + (data.topNotViewNum > 0 ? '<em>'+data.topNotViewNum+'</em>' : ''));
                    }else if(index == 1) {
                        $item.html(data.viewNum + (data.viewNotViewNum > 0 ? '<em>'+data.viewNotViewNum+'</em>' : ''));
                    }else if(index == 2) {
                        $item.html(data.dateNum + (data.dateNotViewNum > 0 ? '<em>'+data.dateNotViewNum+'</em>' : ''));
                    }else{
                        $item.html(data.dateResultNum + (data.dateResultNotViewNum > 0 ? '<em>'+data.dateResultNotViewNum+'</em>' : ''));
                    }
                    
                });
            }
        });
    }

    function renderTalk() {
        fetchTalk(function(list) {
        	var $talk = $('.content-talk');
            var html = list.reduce(function(memo, item) {
                return memo + getTalkHtml(item);
            }, '');
            if(talkPage.page == 1) {
            	$('.talk-list', $talk).html(html || '<div class="no-data">暂无留言</div>');
            }else{
            	$('.talk-list', $talk).append(html);
            }
            $('.infinite-box', $talk).html(list.length == talkPage.size ? '<div class="infinite-scroll-preloader"><div class="preloader"></div></div>' : '');
        });
    }

    function fetchTalk(callback) {
        $.ajax({
            type: 'GET',
            url: HOST + '/api/comment/list',
            data: {
                openid: SELFID,
                page: talkPage.page,
                size: talkPage.size
            },
            success: function(res) {
                callback && callback(res.content);
            }
        });
    }

    function renderRemind(tab, callback) {
        fetchRemindList(tab, function(data) {
            var html = getRemindHtml(tab, data);
            if(remindPage.page == 1) {
                $('.remind-list .card-content-inner').html(html|| '<div class="no-data">暂无消息</div>');
                // $('[data-type='+tab+']').find('.nav-total').html(data.topNum||data.viewNum||data.users.length);
            }else{
                 $('.remind-list .card-content-inner').append(html);
            }
            $('.content-remind .infinite-box').html(data.users.length == 8 ? '<div class="infinite-scroll-preloader"><div class="preloader"></div></div>' : '');
            callback && callback();
        });
    }

    function fetchRemindList(type, callback) {
        $.ajax({
            type: 'GET',
            url: HOST + '/api/user/remind/'+type,
            data: {
                openid: SELFID,
                page: remindPage.page,
                size: remindPage.size
            },
            success: function(res) {
                callback && callback(res.content[type]);
            }
        });
    }

    function getRemindHtml(type, data) {
        if(type == 'top') {
            return data.users.reduce(function(memo, item) {
                return memo + getTopItemHtml(item);
            }, '');
        }else if(type == 'view') {
            return data.users.reduce(function(memo, item) {
                return memo + getWatchItemHtml(item);
            }, '');
        }else if(type == 'dates'){
            return data.users.reduce(function(memo, item) {
                return memo + getDateItemHtml(item);
            }, '');
        }else if(type == 'results') {
            return data.users.reduce(function(memo, item) {
                return memo + getResultItemHtml(item);
            }, '');
        }
    }

    function returnHandle(e) {
        var $item = $(e.target).closest('.content-talk-item');
        $.confirm('<textarea></textarea>', function(elem) {
            var val = $(elem).find('textarea').val();
            if(!val) {
                $.alert('内容不能为空！');
                returnHandle(e);
                return;
            }
            $.ajax({
                url: HOST + '/api/comment/create',
                type: 'post',
                data: JSON.stringify({
                    openid: SELFID,
                    message: val,
                    parentid: $item.data('id'),
                    messagedOpenid: $item.data('openid')
                }),
                success: function(res) {
                    if(res.content == 'success') {
                        renderTalk();
                        return;
                    }
                }
            })
        });
    }

    function agreeHandle(e) {
    	e.stopPropagation();
    	$.showPreloader('请稍等...');
    	$.ajax({
    		url: HOST + '/api/travel/handleDate',
    		type: 'POST',
    		data: JSON.stringify({
    			dateId: $(e.currentTarget).closest('.date').data('did'),
    			result: 2
    		}),
    		success: function(res) {
    			$.hidePreloader();
    			if(res.content == 'success') {
    				$.alert('同意成功，祝你们玩的开心！');
                    renderRemind('dates');
    				return;
    			}
    			$.alert('同意失败，请联系管理员');
    		},
    		error: function() {
    			$.hidePreloader();
    			$.alert('同意失败，请联系管理员');
    		}
    	});
    }

    function refuseHandle(e) {
    	e.stopPropagation();
    	$.showPreloader('请稍等...')
        $.ajax({
            url: HOST + '/api/travel/handleDate',
            type: 'POST',
            data: JSON.stringify({
                dateId: $(e.currentTarget).closest('.date').data('did'),
                result: 1
            }),
            success: function(res) {
            	$.hidePreloader();
                if(res.content == 'success') {
                    $.alert('拒绝成功！');
                    renderRemind('dates');
                    return;
                }
                $.alert('拒绝失败，请联系管理员');
            },
            error: function() {
            	$.hidePreloader();
                $.alert('拒绝失败，请联系管理员');
            }
        });
    }

    function infiniteHandle() {
        var loading = false;
        var I = 0;
        return function() {
            if(loading || $('.content-'+curPage+' .infinite-scroll-preloader').length == 0) {
                return;
            }
            loading = true;
            if(I) {
                clearTimeout(I);
            }
            I = setTimeout(function() {
            	if(curPage == 'remind') {
            		remindPage.page += 1;
                	renderRemind($('.filter-nav .active').data('type'));
            	}else if(curPage == 'talk') {
            		talkPage.page += 1;
            		renderTalk();
            	}
                
                loading = false;
            }, 500);
        }
    }

    function getTopItemHtml(data) {
        if(data.createdAt) {
            var date = new Date(data.createdAt * 1000);
            date = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes();
        }
        return '<div class="common top" data-id="'+data.openid+'" data-apply="'+(data.isApply||'')+'">\
                    <div class="left"><img src="'+data.imgUrl+'"></div>\
                    <div class="middle">\
                        <div>'+(data.name||'未知用户')+'</div>\
                        <div>'+['','男','女'][data.gender]+' | '+data.age+'岁 | '+(data.supportTeams||'暂无支持球队')+' | '+data.peerNum+'人</div>\
                    </div>\
                    <div class="right">\
                        <div class="date">'+(data.createdAt ? date : '')+'</div>\
                        <div class="agree j-top '+(data.isUp?'agree-active':'')+'"></div>\
                    </div>\
                </div>';
    }

    function getWatchItemHtml(data) {
        if(data.createdAt) {
            var date = new Date(data.createdAt * 1000);
            date = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes();
        }
        return '<div class="common view" data-id="'+data.openid+'" data-apply="'+(data.isApply||'')+'">\
                    <div class="left"><img src="'+data.imgUrl+'"></div>\
                    <div class="middle">\
                        <div>'+(data.name||'未知用户')+'</div>\
                        <div>'+['','男','女'][data.gender]+' | '+data.age+'岁 | '+(data.supportTeams||'暂无支持球队')+' | '+data.peerNum+'人</div>\
                    </div>\
                    <div class="right">\
                        <div class="date">'+(data.createdAt ? date : '')+'</div>\
                    </div>\
                </div>';
    }

    function getDateItemHtml(data) {
    	var result = '';
    	if(data.result == 1){
    		result +='已拒绝对方邀请';
    	}else if(data.result == 2) {
    		result +='已接受对方邀请';
    	}else if(data.result == 3) {
    		result += '<a href="#" class="button button-fill j-agree">同意</a><a href="#" class="button button-fill j-refuse" style="margin-left:0.3rem;">婉拒</a>';
    	}else {}
    	if(data.createdAt) {
            var date = new Date(data.createdAt * 1000);
            date = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes();
        }
        return '<div class="common date" data-id="'+data.openid+'" data-did="'+data.dateId+'" data-apply="'+(data.isApply||'')+'">\
                    <div class="left"><img src="'+data.imgUrl+'"></div>\
                    <div class="middle">\
                        <div>'+(data.name||'未知用户')+'</div>\
                        <div>'+(data.createdAt ? date : '')+'</div>\
                    </div>\
                    <div class="right">'+result+'</div>\
                </div>';
    }

    function getResultItemHtml(data) {
        return '<div class="common result" data-apply="'+(data.isApply||'')+'" data-id="'+data.openid+'">\
                    <div class="left"><img src="'+data.imgUrl+'"></div>\
                    <div class="middle">\
                        <div>'+(data.name||'未知用户')+'</div>\
                        <div>'+data.createdAt+'</div>\
                    </div>\
                    <div class="right">对方'+['', '已同意','已拒绝','还没有回音'][data.result||3]+'</div>\
                </div>';
    }


    function getTalkHtml(data) {
        var html = data.children.reduce(function(memo, item) {
            return memo + getReturnHtml(item, data);
        }, '');
        return '<div class="content-talk-item" data-openid="'+data.openid+'" data-id="'+data.id+'">\
                    <div>\
                        <img src="'+data.imgUrl+'">\
                        <div class="name">'+data.name+'</div>\
                        <div class="date">'+parseDateStamp(data.createdAt)+'</div>\
                    </div>\
                    <div class="second">\
                        <div class="text">'+data.content+'</div>\
                        <span class="return-btn j-return">回复</span>\
                    </div>\
                    <div class="return-list">'+html+'</div>\
                </div>';
    }

    function getReturnHtml(data, parent) {
        return  '<div class="return-item">\
                    <span class="name1">'+data.name+'</span>\
                    回复\
                    <span class="name1">'+parent.name+'</span>:\
                    <div class="text1">'+data.content+'</div>\
                </div>';
    }

   
})	
